import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/check_in_info_state.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class DueIn extends StatefulWidget {
  final int checkInId;
  const DueIn({super.key, required this.checkInId});

  @override
  State<StatefulWidget> createState() => _DueInState();

}

class _DueInState extends State<DueIn> {
  final ScrollController _scrollController = ScrollController();

  bool _managed = false;
  List _selectList = [];
  List _list = [];
  int _total = 0;
  bool _isLoading = false;
  double _dueInTotalMoney = 0;
  int _roomId = -1;
  Map<String, dynamic> _params = {
    "pageSize": 10,
    "pageNum": 1,
    "status": 1,
    "checkInId": null
  };
  final List _operation = [{
    "label": "公寓收款码",
    "value": 0,
  }, {
    "label": "完成收款",
    "value": 1,
  }, {
    "label": "催缴",
    "value": 2,
  }, {
    "label": "删除账单",
    "value": 3,
  }, {
    "label": "冻结钥匙",
    "value": 4,
  }];

  Future<void> _getCompleteList() async {
    _isLoading = true;
    Map resData = await billApi.getBillList(_params);
    List data = resData["data"]["rows"] ?? [];
    setState(() {
      _isLoading = false;
      _list.addAll(data);
      _total = resData["data"]["total"] ?? 0;
      _dueInTotalMoney = Utils.toDouble(resData["data"]["dueInTotalMoney"]);
    });
  }

  void _batchRemove() async {
    EasyLoading.show();
    await billApi.batchRemove(_selectList.join(","));
    setState(() {
      _selectList = [];
      _managed = false;
    });
    EasyLoading.dismiss();
    _refresh();
  }

  Future<void> _removeBill(int billId) async {
    EasyLoading.show();
    await billApi.removeBill(billId);
    EasyLoading.dismiss();
  }

  void _showQRCode(BuildContext context) {
    String qrUrl = "https://www.ctqct.net/weixin/index";
    Utils.showQRCode(context, url: qrUrl, title: "公寓收款码");
  }

  Future<void> _refresh() async {
    _params["pageNum"] = 1;
    _list = [];
    _getCompleteList();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getCompleteList();
      });
    }
  }

  bool _selectAll() {
    return _list.length == _selectList.length && _list.isNotEmpty && _selectList.isNotEmpty;
  }

  void _showBottomSheet(Map bill) async {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          width: double.infinity,
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    color: Colors.white
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: List.generate(_operation.length * 2 - 1, (index) {
                    if (index.isOdd) {
                      return const SolidDivider();
                    }
                    Map item = _operation[index ~/ 2];
                    return GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        Navigator.of(context).pop();
                        switch (item["value"]) {
                          case 0:
                              _showQRCode(context);
                            break;
                          case 1:
                            Stacker.pushNamed(Keys.BILL_COLLECTING, arguments: bill)
                                .then((value) {
                              if (value != null && value as bool) {
                                _refresh();
                              }
                            });
                            break;
                          case 2:
                            break;
                          case 3: // 删除账单
                            taiDialog(
                                context: context,
                                child: const Text("确定删除账单？", textAlign: TextAlign.center,),
                                onConfirm: (taiContext) async {
                                  await _removeBill(bill["billId"]);
                                  _refresh();
                                  Stacker.pop();
                                }
                            );
                            break;
                          case 4:
                            break;
                        }
                      },
                      child: SizedBox(
                        height: 48,
                        child: Center(
                          child: Text(item["label"]),
                        ),
                      ),
                    );
                  }),
                ),
              ),
              const SizedBox(height: 12,),
              Button(
                  type: ButtonType.normal,
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text("取消", style: TextStyle(color: ThemeVars.colorText),)
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _listItem(Map item) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (_managed) {
          setState(() {
            _selectList.contains(item["billId"])
                ? _selectList.remove(item["billId"])
                : _selectList.add(item["billId"]);
          });
        } else {
          _showBottomSheet(item);
        }
      },
      child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 12),
          child: Row(
            children: [
              if (_managed)
                _selectList.contains(item["billId"])
                    ? Icon(Icons.check_box_rounded, color: ThemeVars.colorPrimary, size: 18,)
                    : Icon(Icons.check_box_outline_blank_outlined, color: ThemeVars.colorTextTer, size: 18,),
              if (_managed) SizedBox(width: 16,),
              Expanded(
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(item["name"], style: const TextStyle(fontSize: 16),),
                        Text(
                          "${item["inoutFlag"] == "1" ? "+" : "-"}${Utils.formatCurrency(item["money"])}",
                          style: TextStyle(color: item["inoutFlag"] == "1" ? ThemeVars.colorSuccess : ThemeVars.colorError),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4,),
                    Row(
                      children: [
                        Text(
                          "账单周期：${DateTools.formatYMD(item["billCycleBegin"])} - ${DateTools.formatYMD(item["billCycleEnd"])}",
                          style: const TextStyle(fontSize: 14, color: ThemeVars.colorTextTer),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("待收日期：${DateTools.formatYMD(item["noticeDate"])}", style: const TextStyle(fontSize: 14, color: ThemeVars.colorTextTer),),
                        Text(item["receiverName"], style: const TextStyle(fontSize: 14),)
                      ],
                    )
                  ],
                ),
              )
            ],
          )
      ),
    );
  }

  Widget _renderList () {
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "待收：${Utils.formatCurrency(_dueInTotalMoney)}",
                style: const TextStyle(fontSize: 14, color: ThemeVars.colorSuccess),
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () => setState(() {
                  _managed = !_managed;
                }),
                child: const Text("管理", style: TextStyle(color: ThemeVars.colorPrimary),),
              )
            ],
          ),
        ),
        const SolidDivider(),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
          child: Column(
            children: List.generate(_list.length * 2 - 1, (index) {
              if (index.isOdd) {
                return const SolidDivider();
              }
              Map item = _list[index ~/ 2];
              return _listItem(item);
            }),
          ),
        ),
      ],
    );
  }

  @override
  void didChangeDependencies() {
    _params["checkInId"] = CheckInInfoState.of(context)?.info["checkInId"];
    _roomId = CheckInInfoState.of(context)?.info["roomId"];
    _getCompleteList();
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        top: false,
        bottom: false,
        child: Stack(
          children: [
            Builder(
              builder: (BuildContext context) {
                return RefreshIndicator(
                  onRefresh: _refresh,
                  child: CustomScrollView(
                    controller: _scrollController,
                    key: const PageStorageKey<String>("待收账单"),
                    slivers: <Widget>[
                      SliverOverlapInjector(
                        // This is the flip side of the SliverOverlapAbsorber
                        // above.
                        handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                      ),
                      SliverPadding(
                          padding: const EdgeInsets.only(bottom: 72),
                          sliver: SliverToBoxAdapter(
                              child: Container(
                                  decoration: const BoxDecoration(
                                    color: Colors.white,
                                  ),
                                  child: _list.length == 0
                                      ? EmptyData()
                                      : _renderList()
                              )
                          )
                      ),
                    ],
                  ),
                );
              },
            ),
            Positioned(
              bottom: 0,
              left: 0,
              width: MediaQuery.of(context).size.width,
              child: Container(
                padding: const EdgeInsets.all(ThemeVars.paddingPage),
                decoration: BoxDecoration(
                  color: _managed ? Colors.white : ThemeVars.colorBackground,
                ),
                child: _managed
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              setState(() {
                                if (_selectAll()) {
                                  _selectList = [];
                                } else {
                                  _selectList = _list.map((item) => item["billId"]).toList();
                                }
                              });
                            },
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                _selectAll()
                                    ? Icon(Icons.check_circle_rounded, size: 18, color: ThemeVars.colorPrimary,)
                                    : Icon(Icons.circle_outlined, size: 18, color: ThemeVars.colorTextTer),
                                SizedBox(width: 2,),
                                Text("全选", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 12),)
                              ],
                            ),
                          ),
                          Row(
                            children: [
                              Button(
                                type: ButtonType.primary,
                                onPressed: () {
                                  _batchRemove();
                                },
                                child: const Text("删除"),
                              ),
                              const SizedBox(width: 12,),
                              Button(
                                type: ButtonType.primaryOutline,
                                onPressed: () {
                                  setState(() {
                                    _selectList = [];
                                    _managed = false;
                                  });
                                },
                                child: const Text("取消"),
                              )
                            ],
                          )
                        ],
                      )
                    : Button(
                        type: ButtonType.primary,
                        onPressed: () {
                          Stacker.pushNamed(
                            Keys.CHECK_IN_DETAIL_DUE_IN_ADD,
                            arguments: {"initialIndex": 0, "checkInId": widget.checkInId, "roomId": _roomId}
                          ).then((value) {
                            if (value != null && value as bool && value) {
                              _refresh();
                            }
                          });
                        },
                        child: const Text("添加待收账单")
                      ),
              )
            ),
          ],
        )
    );
  }

}